from django.db import models
from utils.Base_model import Base


# Create your models here.


class Paths(Base):
    title = models.CharField("路径名称", max_length=32)
    desc = models.CharField('描述', max_length=256)
    img = models.ImageField(upload_to='paths', null=True)
    follow = models.IntegerField('加入人数',default=0)

    class Meta:
        db_table = 'tb_paths'

    def count_course(self):
        # 计算课程总数
        count = 0
        for stage in self.stage_set.all():
            count += stage.course.count()
        return count

    def count_length(self):
        # 计算课程总时间
        count = 0
        for stage in self.stage_set.all():
            for course in stage.course.all():
                count += course.count_length()
        return round(count / 60, 2)

    def __str__(self):
        return self.title


class Stage(Base):
    title = models.CharField("阶段名称", max_length=32)
    sequence = models.IntegerField('序号', default=1)
    path = models.ForeignKey(Paths, on_delete=models.CASCADE)
    course = models.ManyToManyField('course.Course')

    class Meta:
        db_table = 'tb_stage'
        ordering = ['sequence']

    def __str__(self):
        return '%s-%s' % (self.path.title, self.title)


class UserPath(Base):
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)
    path = models.ForeignKey(Paths, on_delete=models.CASCADE)

    class Meta:
        db_table = 'tb_user_path'


# 路径评论表

class PathComment(Base):
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)
    path = models.ForeignKey(Paths, on_delete=models.CASCADE)
    content = models.TextField('评论内容')
    to = models.ForeignKey('self', null=True, verbose_name='回复谁', on_delete=models.CASCADE)

    class Meta:
        db_table = 'tb_path_comment'
        ordering = ['c_time']

    def __str__(self):
        if self.to:
            return '%s-%s to %s' % (self.path.title, self.user.nick_name, self.to.user.nick_name)
        return '%s-%s' % (self.path.title, self.user.nick_name)
